package com.sunchis.adapter;

import java.util.List;

import com.sunchis.activity.MainActivity;
import com.sunchis.activity.R;
import com.sunchis.util.MyHttpClientManager;
import com.sunchis.util.MyHttpClientManager.ImageBitmapCallback;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {
	private List<String> imageUrls;       //图片地址list
	private Context context;
	private Gallery gallery;
	
	private final LayoutInflater inflater;
	private MyHttpClientManager httpClientManager = new MyHttpClientManager();
	
	public MyAdapter(Context mContext, Gallery myGallery, List<String> imageUrls) {
		this.context = mContext;
		this.gallery = myGallery;
		this.imageUrls = imageUrls;
		
		this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	@Override
	public int getCount() {
		return imageUrls.size();
	}

	@Override
	public Object getItem(int position) {
		return imageUrls.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.item, null);
			
			holder = new ViewHolder();
			holder.photo = (ImageView) convertView.findViewById(R.id.gallery_image);
			holder.text = (TextView) convertView.findViewById(R.id.gallery_text);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		holder.photo.setTag(imageUrls.get(position));
		Bitmap cacheBitmap = httpClientManager.asyncLoadImageBitmap(imageUrls.get(position), new ImageBitmapCallback() {
			public void imageLoaded(Bitmap imageBitmap, String imageUrl) {
				ImageView imageViewByTag = (ImageView) gallery.findViewWithTag(imageUrl);
				if (imageViewByTag != null) {
                    imageViewByTag.setImageBitmap(imageBitmap);
                }
			}
		});
		
		holder.photo.setImageBitmap(cacheBitmap);
		((MainActivity)context).changePointView(position);
		return convertView;
	}

	static class ViewHolder {
		ImageView photo;
		TextView text;
	}
}
